<?php

namespace app\api\controller;
use think\Controller;
use alidayu\TopClient;
use alidayu\AlibabaAliqinFcSmsNumSendRequest;
use data\Json;
use think\Log;
use think\Cache;
/**
 * 接口控制器基类
 */
class Base extends Controller
{
    public function _empty($name)
    {
        // 空方法操作
        return Json::json_send(4);
    }
    
    // 发送短信验证码
    public function sendSMS($mobile,$prefix='')
    {
        $number = randCode();
        $product="圈子";
        $c = new TopClient();
        $c->appkey = config('aliyun_SMS.appkey');
        $c->secretKey = config('aliyun_SMS.secretKey');
        $req = new AlibabaAliqinFcSmsNumSendRequest;
                
        $req->setSmsType("normal");
        $req->setSmsFreeSignName(config('aliyun_SMS.signName'));
        $req->setSmsParam("{\"code\":\"$number\",\"product\":\"$product\"}");
       // $req->setSmsParam("{\"customer\":\"$number\",\"product\":\"$product\"}");
        $req->setRecNum($mobile);
        $req->setSmsTemplateCode(config('aliyun_SMS.templateCode'));
        $resp = $c->execute($req);
        Log::record('common sendSMS resp = '.print_r($resp,1));
        if(isset($resp->code))
        {
            return Json::json_send(401);
        }
        
        if($resp->result->err_code == 0)
        {
            // 将发送的短信验证码放到缓存中，5分钟过期
            //Cache::set($prefix.$mobile, $number, '300');
            Cache::set($prefix.$mobile, $number, '86400');
            return Json::json_send(0,"短信发送成功");
        }
        else
        {
            return Json::json_send(402);
        }
    }

    /**
     * 图片上传接口
     * @return [type] [description]
     */
     public function upload($file)
    {
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size'=>11155678,'ext'=>'jpg,png,gif'])->rule('md5')->move(ROOT_PATH .'public'. DS . 'uploads');
        $url = DS .'uploads/'.$info->getSaveName(); 
        return stripslashes($url);
    }

    /**
     * 多图片上传接口
     * @return [type] [description]
     */
    public function multiUpload($files)
    {
        $images = [];
        foreach ($files as $file) 
        {
            $info = $file->validate(['size'=>11155678,'ext'=>'jpg,png,gif'])->rule('md5')->move(ROOT_PATH .'public'. DS . 'uploads');
            if($info)
            {
                $url = DS . 'uploads/'.$info->getSaveName(); 
                Array_push($images, stripslashes($url)); 
            }
            else
            {
                return $this->sendError(406);
            }  
        }
        return $images;
    }
}
 